package com.library.servlet;

import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.library.dao.BookTitle;
import com.library.dao.BookTitleDAO;
import com.library.dao.DAOFactory;
import com.library.dao.MySQLBookTitleDAO;
import com.library.dao.MySQLDAOFactory;
import com.library.dao.Reservation;
import com.library.dao.ReservationDAO;
import com.library.dao.User;
import com.library.dao.UserDAO;

/**
 * Servlet implementation class Reverse
 */
@WebServlet("/Reverse")
public class Reverse extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Reverse() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String address ="";
		try{
			String id = request.getParameter("id");
			int bookId = Integer.parseInt(id);
			DAOFactory factory = new MySQLDAOFactory();
			BookTitleDAO bookTitleDAO = factory.getBookTitleDAO();
			BookTitle book = bookTitleDAO.findByKey(bookId);
			ReservationDAO resDAO = factory.getReverationDAO();
			if (book != null){
				// neu ma sach dien la hop le
				// kiem tra quyen dat sach
				HttpSession session = request.getSession();
				User instantUser = (User)session.getAttribute("instantUser");
				UserDAO userDAO = factory.getUserDAO();
				int noBook = userDAO.NoOfBorrowtedBook(instantUser.getUserId(), Resource.CONTINUOUS);
				int avail = bookTitleDAO.getNoBookWithState(Resource.AVAILABLE, book.getBookTitleId());
				boolean overDate = userDAO.checkOverdateBook(instantUser.getUserId());
				boolean lendNum = lendindLessThan(noBook);// sach dang muon
				boolean reverseCondition = checkReversedBook(instantUser.getUserId(), bookId, resDAO);
				if ((!overDate) && (!lendNum) && (!reverseCondition) && (avail < 1)){
					Reservation res = new Reservation();
					res.setBookTitleId(bookId);
					res.setUserId(instantUser.getUserId());
					res.setDate(new Date((new java.util.Date()).getTime()));
					ReservationDAO reservationDAO = factory.getReverationDAO();
					reservationDAO.insert(res);			
					
					request.setAttribute("reservarion", res);
					request.setAttribute("book", book);
					address = "user/userresersebookresult.jsp";		
				} else {
					String notification = "";
					if (overDate)
						notification = Resource.ERROR_OVER_DATE;
					else if (lendNum)
						notification = Resource.RESERVATION_NOTIFICATION_LEND;
					else if (reverseCondition)
						notification = Resource.RESERVATION_NOTIFICATION_RESERVED;
					else if (avail > 0)
						notification = Resource.RESERVATION_NOTIFICATION_BOOK_AVAILABLE;
					
					request.setAttribute("notification", notification);
					address = "user/userreverseerror.jsp";
				}
				
			} else {
				String notification = Resource.NOTIFICATION_XBOOK;
				request.setAttribute("notification", notification);
				address = "user/userreverseerror.jsp";
			}
		} catch (Exception e){
			String notification = "Lỗi nhập dữ liệu";
			request.setAttribute("notification", notification);
			address = "user/userreverseerror.jsp";
		}
		
		
		RequestDispatcher dispatcher =
			      request.getRequestDispatcher(address);
			    dispatcher.forward(request, response);
	}
	
	private boolean checkBorrowedBook(int userId, int bookId,UserDAO dao){
		// danh sach sach dang muon
		ArrayList<BookTitle> list = dao.getBorrowedBook(userId, Resource.CONTINUOUS);
		for (BookTitle b: list)
			if (b.getBookTitleId() == userId)
				return true;// muon roi
		return false;
	}
	
	private boolean checkReversedBook(int userId, int bookId, ReservationDAO dao){
		ArrayList<Reservation> list =  dao.findReservedBook(userId);
		for(Reservation res : list)
			if (res.getBookTitleId() == bookId)
				return true;// dat roi 
		return false; 
	}
	
	private boolean lendindLessThan(int noBook){
		if (noBook < Resource.MAX_BOOK)
			return false;
		return true;
	}

}
